//
//  AppDelegate.swift
//  Weibo
//
//  Created by 付启刚 on 15/12/12.
//  Copyright © 2015年 faq. All rights reserved.
//

import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        let account=UserAccount.loadAccount()//类方法 class前缀修饰
        print(account)
        window=UIWindow(frame: UIScreen.mainScreen().bounds)
        window?.backgroundColor=UIColor.whiteColor()
        window?.makeKeyAndVisible()
        //设置整个主题的颜色
        setThemeColor()
        registerNotification()
        //设置根控制器
//        window?.rootViewController=MainViewController()
      window?.rootViewController=defaultViewController()
        return true
    }
    //注册通知,通知页面进行跳转
 private func registerNotification(){
    NSNotificationCenter.defaultCenter().addObserver(self, selector: "switchRootVC:", name: WBSwitchRootVCNotification, object: nil)
    }
    //移除通知操作 写与不写没多大关系 主要是习惯问题
    deinit{
    NSNotificationCenter.defaultCenter().removeObserver(self)
    }
    @objc private func switchRootVC(n:NSNotification){
   // print(n)
        //根据通知去切换对应根视图控制器
         if  n.object != nil {
        //跳转到welcome
            window?.rootViewController=WelcomeViewController()
            return
        }
        //跳到首页
        window?.rootViewController=MainViewController()
    }
    //根据用户是否登录显示具体的页面
    private func defaultViewController()->UIViewController{
    //根据用户是否登录
        if UserAccountViewModel().userLogin{
//            登录
        return isNewVersion() ? NewFeatureViewController() : WelcomeViewController()
        }
        //没登陆
        return MainViewController()
    }
    private func isNewVersion()->Bool{
        //获取当前应用版本
    let info=NSBundle.mainBundle().infoDictionary
        let currentStr=info!["CFBundleShortVersionString"] as!String
        let currentNum=Double(currentStr)
        print(currentNum)
        //2.获取本地缓存的版本
        //用userDefaults 来存储版本
        let userDefault = NSUserDefaults.standardUserDefaults()
        let sandBoxKey="sandBox"
        let lastNum = userDefault.doubleForKey(sandBoxKey)
        //3. 立即存储 当前应用的版本号
      userDefault.setDouble(currentNum!, forKey: sandBoxKey)
//        立即存储
        userDefault.synchronize()
        return currentNum! > lastNum
    }
    //设置主题颜色 一定要尽早设置
    private func setThemeColor(){
    UINavigationBar.appearance().tintColor=themeColor
        UITabBar.appearance().tintColor=themeColor
    }
}

